<?php

namespace app\common\model\Product;

use think\Model;
use traits\model\SoftDelete;
use think\Env;
class Product extends Model
{
    protected $name = 'product';
    protected $autoWriteTimestamp = true;

    protected $createTime = 'createtime';

    protected $updateTime = false;
    use SoftDelete;
    protected $deleteTime = 'deletetime';
    protected $append = [
        'thumbs_text', //产品单张图
        'thumbs_list', //产品多张图
        'content_text' //内容去除标签
    ];

    public function getThumbsTextAttr($value, $data)
    {
        $url = Env::get('site.url', config('site.url'));

        $thumbs_text = '';

        $thumbs = !empty($data['thumbs']) ?  explode(',', $data['thumbs']) : [];

        if (count($thumbs) > 0) {
            $thumbs_text = $url . $thumbs[0];
        } else {
            $thumbs_text = $url . '/assets/img/a.jpg';
        }

        return $thumbs_text;
    }
    public function getContentTextAttr($value, $data)
    {
        $content = !empty($data['content']) ? $data['content'] : '';
        return strip_tags($content);
    }
    public function getThumbsListAttr($value, $data)
    {
        $url = Env::get('site.url', config('site.url'));
        $thumbs_text = '';

        $thumbs = !empty($data['thumbs']) ?  $data['thumbs'] : [];

        if (!empty($thumbs)) {
            $thumbs = str_ireplace("/uploads/", $url . "/uploads/", $thumbs);
            $thumbs_text = explode(',', $thumbs);
        } else {
            $thumbs_text = [$url . '/assets/images/a.jpg'];
        }

        return $thumbs_text;
    }
    // 关联查询（根据业务需求）
    public function type()
    {
        /* 
             belongsTo 相应关联查询
                 第一个参数 model => 需要关联模型
                 第二个参数 foreignKey => 外键
                 第三个参数 locaKey => 主键
                 第四个参数 alias => 模型别名
                 第五个参数 joinType => 链表查询（LEFT，INNER，RIGHT）
 
             setEagerlyType 设置预载入方法
                 0 => JOIN查询
                 1 => IN查询
         */
        return $this->belongsTo('app\common\model\Product\Type', 'typeid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

     // 关联查询（根据业务需求）
     public function unit()
     {
         return $this->belongsTo('app\common\model\Product\Unit', 'unitid', 'id', [], 'LEFT')->setEagerlyType(0);
     }
}
